
package com.yimixian.app.address;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.location.LocatedListener;
import com.yimixian.app.location.LocationProvider;
import com.yimixian.app.model.Address;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.util.ObservableUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import java.util.ArrayList;
import java.util.List;

public class ShowAddressesActivity extends AbstractAddressActivity {

    public static final String EXTRA_MODE = "extra_mode";

    public static final int PICK_ADDRESS_MODE = 0;
    public static final int MANAGE_ADDRESS_MODE = 1;
    public static final int LOCATE_ADDRESS_MODE = 2;

    @InjectView(R.id.locating_button)
    FrameLayout mLocatingButton;
    @InjectView(R.id.addresses_view)
    AddressesView mAddressesView;
    @InjectView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @InjectView(R.id.locating_icon)
    ImageView mLocatingIcon;
    @InjectView(R.id.locating_text)
    TextView mLocatingText;
    @InjectView(R.id.loading)
    ProgressBar mLoadingView;

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt(EXTRA_MODE, mMode);
    }

    @Override
    public void resumeOnCreate() {
        if (mDataManager != null) {
            return;
        }

        mDataManager = DataManager.getInstance();
        mYmxDataService = YmxDataService.getInstance();

        setContentView(R.layout.show_addresses_activity);
        ButterKnife.inject(this);
        setAddressViewListener(mAddressesView, mDataManager, false);

       /* if (mMode == MANAGE_ADDRESS_MODE) {
            mAddressesView.disableAddressClickListener();
        }*/

        mLocatingButton.setVisibility(mMode == LOCATE_ADDRESS_MODE ? View.VISIBLE : View.GONE);

        fetchAddress(true);
    }

    private void fetchAddress(final boolean readFromCache) {
        mYmxDataService.getAddresses(readFromCache)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<List<Address>>() {
                            @Override
                            public void call(List<Address> addresses) {
                                mLoadingView.setVisibility(View.GONE);
                                if (!readFromCache) {
                                    SharedPreferencesHelper.saveAddresses((ArrayList) addresses, SharePreferenceKeys.ADDRESSES);
                                }
 
                                mAddressesView.bind(addresses, true);
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {

                            }
                        }
                );
    }

    @OnClick({
            R.id.locating_button
    })
    public void onLocatingButtonClicked(final FrameLayout locatingButton) {
        MobclickAgent.onEvent(this, StatConstants.MANAGER_ADDRESS_LOCATE_CLICK);
        locatingButton.setEnabled(false);
        mLocatingText.setText(getString(R.string.locating));
        mLocatingIcon.setVisibility(View.INVISIBLE);
        mProgressBar.setVisibility(View.VISIBLE);

        LocationProvider.getInstance().startBaiduLocated(true, new LocatedListener() {

            @Override
            public void locatedSuccessListener(BDLocation location) {
            }

            @Override
            public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {
                getAction1(poiInfo.location, poiInfo);
            }

            @Override
            public void locatedFailedListener() {
                getErrorAction1();
            }

            @Override
            public void locatedFailedGeoPoiInfoListener() {
                getErrorAction1();
            }
        });
    }

    @Override
    public void onLocatingFailed() {
        UiUtils.showToast(this, getString(R.string.locate_fail));
        mLocatingButton.setEnabled(true);
        mLocatingText.setText(getString(R.string.locate_current_position));
        mLocatingIcon.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    public void stopLocating() {
        if (mMode == MANAGE_ADDRESS_MODE || mLocatingButton.isEnabled()) {
            return;
        }
        mLocatingButton.setEnabled(true);
        mLocatingText.setText(getString(R.string.locate_current_position));
        mLocatingIcon.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    @OnClick({
            R.id.add_address_button
    })
    public void onAddAddressButtonClicked(TextView addAddressButton) {
        MobclickAgent.onEvent(this, StatConstants.MANAGER_ADDRESS_ADD_CLICK);
        stopLocating();
        Intent intent = new Intent(this, ModifyOrCreateAddressActivity.class);
        startActivityForResult(intent, Constants.MODIFY_ADDRESS_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        onREGResult(requestCode, resultCode);
        if (requestCode == Constants.MODIFY_ADDRESS_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                EventBus.getDefault().post(new ShowAdSelectChange());
                startActivity(YMXMainActivity.buildIntentTab(ShowAddressesActivity.this,
                        YMXMainActivity.TAB_HOME));
                finish();
            } else {
                fetchAddress(true);
            }
        }
    }

    @Override
    protected String getTitleBarText() {
        return mMode != MANAGE_ADDRESS_MODE ? "选择收货地址" : "管理收货地址";
    }

    @Override
    public void setTabIndex(Bundle savedInstanceState) {
        return;
    }
}
